import { App, Avatar, Button, Input } from 'antd';
import { TextArea } from 'antd-mobile';
import React, { useCallback, useMemo } from 'react';
import { useContextSelector } from 'use-context-selector';

import MyModal from '@/components/MyModal';
import { useRequest2 } from '@/hooks/use-request';
import { useSelectFile } from '@/hooks/use-select-file';
import { t } from '@/locales/i18n';
import { MongoImageTypeEnum } from '@/pages/chat/tools/constants';
import { getErrText } from '@/pages/chat/tools/utils';
import { compressImgFileAndUpload } from '@/types/app/api';
import { AppSchema } from '@/types/app/type';

import { AppContext } from '../context';

const InfoModal = ({ onClose }: { onClose: () => void }) => {
  const { updateAppDetail, appDetail, reloadApp } = useContextSelector(AppContext, (v) => v);
  const { message } = App.useApp();

  const { File, onOpen: onOpenSelectFile } = useSelectFile({
    fileType: '.jpg,.png',
    multiple: false,
  });

  const [data, setData] = React.useState(appDetail);

  // const {
  //   register,
  //   setValue,
  //   getValues,
  //   formState: { errors },
  //   handleSubmit
  // } = useForm({
  //   defaultValues: appDetail
  // });
  const avatar = useMemo(() => data.avatar, [data]);

  // submit config
  const { runAsync: saveSubmitSuccess, loading: btnLoading } = useRequest2(
    async (data: AppSchema) => {
      await updateAppDetail({
        name: data.name,
        avatar: data.avatar,
        intro: data.intro,
      });
    },
    {
      onSuccess() {
        message.success(t('common.Update Success'));
        reloadApp();
        onClose();
      },
      errorToast: t('common.Update Failed'),
    },
  );
  // TODO
  // const saveSubmitError = useCallback(() => {
  //   // deep search message
  //   const deepSearch = (obj: any): string => {
  //     if (!obj) return t('common.Submit failed');
  //     if (!!obj.message) {
  //       return obj.message;
  //     }
  //     return deepSearch(Object.values(obj)[0]);
  //   };
  //   message.error(deepSearch(errors));
  // }, [errors, t, toast]);

  const saveUpdateModel = useCallback(() => {
    saveSubmitSuccess(data);
    // onClose();
  }, [saveSubmitSuccess, data]);

  const onSelectFile = useCallback(
    async (e: File[]) => {
      const file = e[0];
      if (!file) return;
      try {
        // TODO
        const src = await compressImgFileAndUpload({
          type: MongoImageTypeEnum.appAvatar,
          file,
          maxW: 512,
          maxH: 512,
        });
        setData((prev) => {
          return {
            ...data,
            avatar: src,
          };
        });
      } catch (err: any) {
        message.warning(getErrText(err, t('common.error.Select avatar failed')));
      }
    },
    [setData, message, data],
  );

  // const onUpdateCollaborators = ({
  //   members,
  //   groups,
  //   permission,
  // }: {
  //   members?: string[];
  //   groups?: string[];
  //   permission: PermissionValueType;
  // }) =>
  //   postUpdateAppCollaborators({
  //     members,
  //     groups,
  //     permission,
  //     appId: appDetail._id,
  //   });

  // const onDelCollaborator = async (props: RequireOnlyOne<{ tmbId: string; groupId: string }>) =>
  //   deleteAppCollaborators({
  //     appId: appDetail._id,
  //     ...props,
  //   });

  // const { runAsync: resumeInheritPermission } = useRequest2(() => resumeInheritPer(appDetail._id), {
  //   errorToast: t('resume_failed'),
  //   onSuccess: () => {
  //     reloadApp();
  //   },
  // });

  return (
    <MyModal
      isOpen
      onClose={onClose}
      // iconSrc="/imgs/workflow/ai.svg"
      title={t('core.app.setting')}
      minW="35vw"
      maxW="50vw"
    >
      <div className="flex flex-col gap-2 overflow-hidden">
        <div className="text-sm">{t('core.app.Name and avatar')}</div>
        <div className="mt-2 flex items-center gap-2">
          <Avatar
            src={avatar}
            className="mr-4 cursor-pointer rounded-md"
            // title={t('common.Set Avatar')}
            onClick={() => onOpenSelectFile()}
          />
          <Input
            className="bg-gray-500"
            placeholder={t('core.app.Set a name for your app')}
            value={data.name}
            onChange={(e) => setData((prev) => ({ ...prev, name: e.target.value }))}
          />
        </div>
        <div className="mb-1 mt-4 text-sm">{t('core.app.App intro')}</div>
        <TextArea
          rows={4}
          maxLength={500}
          placeholder={t('core.app.Make a brief introduction of your app')}
          className="rounded-md bg-WhiteSmoke"
          value={data.intro}
          onChange={(e) => setData((prev) => ({ ...prev, intro: e }))}
        />
      </div>

      <div className="ml-auto mt-4 flex">
        <Button className="mr-3" onClick={onClose}>
          {t('common.Close')}
        </Button>
        <Button type="primary" loading={btnLoading} onClick={saveUpdateModel}>
          {t('common.Save')}
        </Button>
      </div>

      <File onSelect={onSelectFile} />
    </MyModal>
  );
};

export default React.memo(InfoModal);
